/*
Copyright (c) 2012 the VATSIM Connector project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef __LIBVATCONN__CONNECTION_H__
#define __LIBVATCONN__CONNECTION_H__

#include "libvatconn.h"
#include <deque>
#include <functional>
#include <cassert>
#include "messages.h"

/**
 * The visualization plugin's interface to the host VATSIM Connector.
 */
class VconConnection
{
public:
  /**
   * Returns a pointer to a new VconConnection object.
   *
   * This should be `delete`d when finished.
   */
  static VconConnection* create();

  /**
   * Virtual destructor.
   */
  virtual ~VconConnection() {}

  /**
   * Set the UDP port numbers used by the visualization plugin (local) and
   * the host connector (remote).
   */
  virtual void setPorts(int local, int remote) = 0;

  /**
   * Set the hostname or IP address where the host connector is expected to
   * be listening.
   */
  virtual void setRemoteHost(char const* addr) = 0;

  /**
   * Set the VATSIM username and password.
   */
  virtual void setUserPass(char const* user, char const* pass) = 0;

  /**
   * Enable the connection. Will begin sending and receiving messages.
   *
   * Returns a null pointer if the call was successful, otherwise returns a
   * human-readable error string.
   */
  virtual char const* enable() = 0;

  /**
   * Disable the connection. Will stop sending and receiving messages.
   */
  virtual void disable() = 0;

  /**
   * Check to see what messages have been received from the connector,
   * and handle them by calling back to the handler provided with
   * `setMessageHandler()`.
   */
  virtual void pollReceivedMessages() = 0;

  /**
   * Send all messages which have been added to the queue with
   * `queueMessages()`, and clear the queue.
   */
  virtual void sendQueuedMessages() = 0;

  /**
   * Add an outgoing message to the queue, ready to be sent with
   * `sendQueuedMessages()`.
   */
  template <class T>
  void queueMessage(T const& msg)
  {
    m_queue.push_back(QueuedMsg(T::typeStr(), VconStringifyMessage(msg)));
  }

  /**
   * Provide an object whose methods will be called to handle incoming
   * messages when `pollReceivedMessages()` is called.
   *
   * The object must have the public instance methods `handleMessagePP()`,
   * `handleMessageWX()`, `handleMessageMG()`, and `handleMessageSQ()`,
   * which each take a single argument (a reference to a
   * `const VconMsgPlanePosition`, `VconMsgWeather`, `VconMsgText`, and
   * `VconMsgSquawk` respectively) and all return void.
   */
  template <class T>
  void setMessageHandler(T& handler)
  {
    using namespace std::tr1::placeholders;
    m_handlerPP = std::tr1::bind(&T::handleMessagePP, &handler, _1);
    m_handlerWX = std::tr1::bind(&T::handleMessageWX, &handler, _1);
    m_handlerMG = std::tr1::bind(&T::handleMessageMG, &handler, _1);
    m_handlerSQ = std::tr1::bind(&T::handleMessageSQ, &handler, _1);
  }

protected:
  struct QueuedMsg
  {
    QueuedMsg(char const* _id, std::string _msg) : id(_id), msg(_msg) {}
    char const* id;
    std::string msg;
  };
  std::deque<QueuedMsg> m_queue;

  std::tr1::function<void(VconMsgPlanePosition	const&)> m_handlerPP;
  std::tr1::function<void(VconMsgWeather	const&)> m_handlerWX;
  std::tr1::function<void(VconMsgText		const&)> m_handlerMG;
  std::tr1::function<void(VconMsgSquawk		const&)> m_handlerSQ;

  bool handleMessage(int id, char const* str, size_t len)
  {
    assert(m_handlerPP);
    assert(m_handlerWX);
    assert(m_handlerMG);
    assert(m_handlerSQ);
    switch (id)
    {
    case VconMsgPlanePosition::typeNum:	{ VconMsgPlanePosition msg;
      if (! VconDestringifyMessage(msg, str, len)) break; m_handlerPP(msg); return true; }
    case VconMsgWeather::typeNum:	{ VconMsgWeather msg;
      if (! VconDestringifyMessage(msg, str, len)) break; m_handlerWX(msg); return true; }
    case VconMsgText::typeNum:		{ VconMsgText msg;
      if (! VconDestringifyMessage(msg, str, len)) break; m_handlerMG(msg); return true; }
    case VconMsgSquawk::typeNum:	{ VconMsgSquawk msg;
      if (! VconDestringifyMessage(msg, str, len)) break; m_handlerSQ(msg); return true; }
    }
    return false;
  }
};

#endif //__LIBVATCONN__CONNECTION_H__